const cloud = require('wx-server-sdk')
cloud.init({env: 'evn-cloud-a-4gf1q6iy9df62d73'})
const db = cloud.database()
const _ = db.command
const paymentDetails = require('./src/opt_paymentDetails.js')

/**获取随机数 */
const getRandomNumber = (len) => {
  len = len || 32
  const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  var maxPos = chars.length;
  let str = ''
  for (let i = 0; i < len; i++) {
    str += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  console.log('生成的随机字符串为：',str)
  return str
}
/**获取payment实体 */
const getPayment = async (event) => {
  const recordResult = await paymentDetails.recordWaitPayOrderNo(event)
  if(!recordResult){
    console.error('记录流水失败.')
    return {returnCode: 'FAIL', returnMsg: '记录流水失败.'}
  }
  console.info('参数为：',event)
  const outTradeNo = event.outTradeNo
  const totalFee = event.totalFee
  const noticeStr = await getRandomNumber(32)
  const data = {
    "body" : "放生款充值",
    "outTradeNo" : outTradeNo,
    "spbillCreateIp" : "127.0.0.1",
    "subMchId" : "1609677766",
    "nonceStr": noticeStr,
    "tradeType": "JSAPI",
    "totalFee" : new Number(totalFee),
    "envId": "evn-cloud-a-4gf1q6iy9df62d73",
    "functionName": "pay"
  }
  console.log('请求参数为：',data + '\n')
  const res = await cloud.cloudPay.unifiedOrder(data)
  console.info('pay返回的结果为：', res + '\n')
  return res
}

//在微信服务器生成订单并返回，记录流水在本地
exports.main = async (event, context) => {
  console.log('pay被访问，参数为：',event)
  const reqType = event.reqType
  switch(reqType){
    case "getPayment":
      return await getPayment(event)
    default:
      console.log('微信服务器通知支付返回.',event)
      return await paymentDetails.waitPayOrderNoTransSuccessOrderNo(event)
  }
}